package com.lhj.xxsc.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.lhj.xxsc.order.config.AlipayTemplate;
import com.lhj.xxsc.order.service.OrderService;
import com.lhj.xxsc.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 罗惠江
 * @version 1.0
 * @email 1511619294@qq.com
 * @date 2021/1/9 14:08
 */
@RestController
public class OrderPayedListener {

	@Autowired
	OrderService orderService;

	@Autowired
	AlipayTemplate alipayTemplate;

	@PostMapping("/payed/notify")
	public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
		// 验签
		//获取支付宝POST过来反馈信息
		System.out.println("支付宝异步回调");
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
		if (signVerified) {
			System.out.println("签名验证成功");

			String result = orderService.handlePayResult(vo);

			return result;
		}else {
			System.out.println("签名验证失败");
			return "error";
		}
	}
}
